<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/5/29
 * Time: 9:54
 */

namespace app\index\controller;

use app\admin\model\Area;
use app\admin\model\MallGoods;
use app\admin\model\SystemFeedback;
use app\admin\model\UserAmountLog;
use app\admin\model\UserArea;
use app\admin\model\UserInfo;
use app\admin\model\UserLevel;
use app\admin\model\UserTransaction;
use think\facade\Db;
use think\facade\Env;
use app\common\command\PhpQrCode;
use app\common\controller\IndexController;
use app\Request;
use ClassLibrary\ClHttp;
use ClassLibrary\ClString;
use app\admin\model\UserReal;

class User extends IndexController {
    //    生成邀请海报
    public function generate(Request $request) {
        $url   = Env::get('domain.url') . '/index/login/add?superior=' . $request->uid;
        $model = new PhpQrCode();
        $res   = $model->generate($url);
        if (file_exists($res)) {
            $url  = ClHttp::getServerDomain();
            $data = explode('./', $res);
            $this->success('OK', $url . '/' . $data[1]);
        } else {
            $this->error('失败');
        }
    }

    public function user_price(Request $request) {
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'type' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $uid             = $request->uid;
        $where           = [
            ['type', '=', $all['type']],
            ['uid', '=', $uid],
        ];
        $data            = UserInfo::where($where)->field('assets,frozen')->find();
        $type_text       = config('cointype')[$all['type']];
        $data->type_text = $type_text;
        $res             = ClHttp::request('https://www.okex.com/api/spot/v3/instruments/' . $type_text . '-USDT/ticker', '', 'json');
        $data->rise      = $data->assets * $res['last'];
        $this->success('OK', $data);
    }

    public function user_info(Request $request) {
        $all   = input();
        $where = [
            ['uid', '=', $request->uid]
        ];
        if (!empty($all['type'])) {
            array_push($where, ['type', '=', $all['type']]);
        }
        $data = UserInfo::where($where)->field('assets,frozen,type')->select()->toArray();
        foreach ($data as $k => $v) {
            $type_text             = config('cointype')[$v['type']];
            $data[$k]['type_text'] = $type_text;
            if ($v['type'] !== 6) {
                $res              = ClHttp::request('https://www.okex.com/api/spot/v3/instruments/' . $type_text . '-USDT/ticker', '', 'json');
                $data[$k]['rise'] = $v['assets'] * $res['last'];
            } else {
                $data[$k]['rise'] = $v['assets'];
            }
        }
        $this->success('OK',$data);
    }

    public function user_info_list(Request $request) {
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'page' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $page  = isset($all['page']) && !empty($all['page']) ? $all['page'] : 1;
        $limit = isset($all['limit']) && !empty($all['limit']) ? $all['limit'] : 15;
        $where[] =[
            ['user_id','=',$request->uid]
        ];
        if(!empty($all['type'])){
            array_push($where,['cointype','=',$all['type']]);
        }
        $data  = UserAmountLog::where($where)->field('amount,create_time,type')->page($page, $limit)->order('id', 'desc')->select()->toArray();
        foreach ($data as $k => $v) {
            $data[$k]['type_text'] = config('logtype')['amount'][$v['type']];
        }
        $this->success('OK', $data);
    }

    public function user_commission(Request $request) {
        $u_id                = $request->uid;
        $user                = \app\admin\model\User::where('u.id', $u_id)->alias('u')->leftJoin('user_level l', 'l.id = u.level_id')->field('l.*')->find()->toArray();

        $data                = [];
        $node_bug_ratio      = explode(',', $user['node_bug_ratio']);//矿机购买
        $node_hosting_ratio  = explode(',', $user['node_hosting_ratio']);//矿机托管
        $node_power_ratio    = explode(',', $user['node_power_ratio']);//租力
        $entrust_plots_ratio = explode(',', $user['entrust_plots_ratio']);//委托P盘
        $deposit_coin_ratio  = explode(',', $user['deposit_coin_ratio']);//存币生息
        $loan_ratio          = explode(',', $user['loan_ratio']);//借贷

        //        我的返佣比例
        $data['proportion'] = [
            0 => [
                'name'  => $node_bug_ratio[0] . '%',
                'value' => '矿机购买：',
            ],
            1 => [
                'name'  => $node_hosting_ratio[0] . '%',
                'value' => '矿机托管：',
            ],
            2 => [
                'name'  => $node_power_ratio[0] . '%',
                'value' => '租力：',
            ],
            3 => [
                'name'  => $entrust_plots_ratio[0] . '%',
                'value' => '委托P盘：',
            ],
            4 => [
                'name'  => $deposit_coin_ratio[0] . '%',
                'value' => '存币生息：',
            ],
            5 => [
                'name'  => $loan_ratio[0] . '%',
                'value' => '借贷：',
            ],
        ];
        //        邀请链接：
        $data['url'] = Env::get('domain.url') . '/index/login/add?superior=' . $u_id;
        //        我的邀请
        $data['superior'] = \app\admin\model\User::where('superior', $u_id)->count();
        //我的返佣
        $UserAmountLog_Model = new UserAmountLog();
        $p                   = $UserAmountLog_Model->field('type,sum(amount) as sum')->where([
            [
                'type',
                'in',
                '1,2,3,4,5'
            ],
            ['user_id', '=', $u_id]
        ])->group('type')->select()->toArray();
        foreach ($p as $k => $v) {
            $p[$k]['type_text'] = preg_replace('/([\x80-\xff]*)/i', '', config('logtype')['amount'][$v['type']]);
        }
        $data['prop'] = $p;
        $this->success('OK', $data);
    }

    public function superior_list(Request $request) {
        $superior = \app\admin\model\User::where('superior', $request->uid)->field('title,image,create_time')->select();
        $this->success('OK', $superior);
    }

    public function prop_list(Request $request) {
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'page' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $page                = isset($all['page']) && !empty($all['page']) ? $all['page'] : 1;
        $limit               = isset($all['limit']) && !empty($all['limit']) ? $all['limit'] : 15;
        $UserAmountLog_Model = new UserAmountLog();
        $p                   = $UserAmountLog_Model->field('type,amount,create_time')->where([
            [
                'type',
                'in',
                '1,2,3,4,5'
            ],
            [
                'user_id',
                '=',
                $request->uid
            ]
        ])->page($page, $limit)->select()->toArray();
        foreach ($p as $k => $v) {
            $p[$k]['type_text'] = preg_replace('/([\x80-\xff]*)/i', '', config('logtype')['amount'][$v['type']]);
        }
        $this->success('OK', $p);
    }





    //用户收货地址管理
    //    列表
    public function user_area_list(Request $request) {
        $user_id = $request->uid;
        $area    = UserArea::where('user_id', $user_id)->select()->toArray();
        foreach ($area as $k => $v) {
            $a                = Area::where('id', $v['area_id'])->find();
            $area[$k]['area'] = str_replace(',', ' ', $a->mername);
        }
        $this->success('OK', $area);
    }

    //添加收货地址
    public function user_area_add(Request $request) {
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'area_id'    => 'require',
            'user_phone' => 'require',
            'user_name'  => 'user_name',
            'detailed'   => 'require',
            'status'     => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $user_id        = $request->uid;
        $all['user_id'] = $user_id;
        if ($all['status'] == 1) {
            UserArea::where('user_id', $user_id)->update(['status' => 0]);
        }
        $res = UserArea::insert($all);
        if ($res) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }

    //    地址修改页面
    public function user_area_edit() {
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'id' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $res            = UserArea::where('u.id', $all['id'])->alias('u')->field('u.id,u.user_phone,u.area_id,u.user_name,u.detailed,a.mername,u.status')->leftJoin('area a', 'a.id = u.area_id')->find()->toArray();
        $res['mername'] = explode(',', $res['mername']);
        $this->success('ok', $res);
    }

    public function user_area_edit_implement(Request $request) {
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'id'         => 'require',
            'area_id'    => 'require',
            'user_name'  => 'require',
            'user_phone' => 'require',
            'detailed'   => 'require',
            'status'     => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $where           = [
            'area_id'    => $all['area_id'],
            'user_phone' => $all['user_phone'],
            'user_name'  => $all['user_name'],
            'detailed'   => $all['detailed'],
            'status'     => $all['status'],
        ];
        $user_area_model = new UserArea();
        $res             = $user_area_model->where('id', $all['id'])->update($where);
        if ($res) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }
    }

    //地址三级联动
    public function area() {
        $all  = input('id');
        $data = Area::where('pid', $all)->field('id,name,pid')->select()->toArray();
        $this->success('OK', $data);
    }

    public function user(Request $request) {
        $user_id = $request->uid;
        $data    = \app\admin\model\User::where('id', $user_id)->field('id,title,image,email,level_id,is_real')->find();
        $this->success($data);
    }

    public function pwd(Request $request) {
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'new_pwd'     => 'require',
            'pwd'         => 'require',
            'confirm_pwd' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        if ($all['pwd'] !== $all['confirm_pwd']) {
            $this->error('设置密码与确认密码不一致');
        }
        $uid  = $request->uid;
        $user = \app\admin\model\User::where('id', $uid)->find();

        if ($user->pwd !== md5($all['new_pwd'])) {
            $this->error('原密码错误');
        }
        $res = \app\admin\model\User::where('id', $uid)->update(['pwd' => md5($all['pwd'])]);
        if ($res) {
            $this->success('设置成功');
        } else {
            $this->error('设置失败');
        }
    }


    public function user_edit(Request $request) {
        $all = input();
        $uid = $request->uid;
        $res = \app\admin\model\User::where('id', $uid)->update($all);
        if ($res) {
            $this->success('修改成功');
        } else {
            $this->error('修改失败');
        }

    }


    /**
     * 用户订单开始
     */
    public function order_type() {
        $model = new \app\admin\model\Order();
        $data  = $model->getTypeList();
        $res   = [];
        array_push($res, ['id' => 0, 'value' => '全部']);
        foreach ($data as $k => $v) {
            array_push($res, ['id' => $k, 'value' => $v]);
        }
        $this->success('查询成功', $res);
    }

    public function user_order(Request $request) {
        $uid      = $request->uid;
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'page' => 'require',
            'type' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $page    = isset($all['page']) && !empty($all['page']) ? $all['page'] : 1;
        $limit   = isset($all['limit']) && !empty($all['limit']) ? $all['limit'] : 15;
        $where[] = [
            ['uid', '=', $uid],
        ];
        if ($all['type'] > 0) {
            array_push($where, ['type', '=', $all['type']]);
        }
        $model = new \app\admin\model\Order();
        $data  = $model->where($where)->field('id,type,type_id,order_number,information,goods_type,days_time,status')->page($page, $limit)->order('id', 'desc')->select()->toArray();
        foreach ($data as $k => $v) {
            $data[$k]['type_text']       = $model->getTypeList()[$v['type']];
            $data[$k]['goods_type_text'] = $model->getGoodsTypeList()[$v['goods_type']];
            $data[$k]['status_text']     = $model->getStatusList()[$v['status']];
            $data[$k]['days_time']       = date('Y-m-d H:i:s', $v['status']);
        }
        $this->success('查询成功', $data);
    }

    public function order_info() {
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'id' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $model                   = new \app\admin\model\Order();
        $data                    = $model->where('id', $all['id'])->field('id,type,type_id,order_number,information,goods_type,uid_phone,address,username,produce_type,money,days_time,status,create_time')->find()->toArray();
        $data['type_text']       = $model->getTypeList()[$data['type']];
        $data['goods_type_text'] = $model->getGoodsTypeList()[$data['goods_type']];
        $data['status_text']     = $model->getStatusList()[$data['status']];
        $data['days_time']       = date('Y-m-d H:i:s', $data['status']);


        $user_amount_model                = new UserAmountLog();
        $user_amount                      = [];
        $where                            = [
            'order_id' => $data['id']
        ];
        $user_amount['produce_type_text'] = config('cointype')[$data['produce_type']];
        $user_amount['count']             = $user_amount_model->where($where)->count();
        $user_amount['amount']            = $user_amount_model->where($where)->sum('amount');
        $user_amount['data']              = $user_amount_model->where($where)->field('amount,create_time')->select();
        $this->success('查询成功', ['order' => $data, 'order_info' => $user_amount]);
    }


    /**
     * 用户提现
     */
    public function user_status() {
        $data = config('cointype');
        $res  = [];
        foreach ($data as $k => $v) {
            array_push($res, ['id' => $k, 'title' => $v]);
        }
        $this->success('OK', $res);
    }

    public function user_withdrawal(Request $request) {
        $user_id  = $request->uid;
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'type'             => 'require',
            'chain'            => 'require',
            'address_carry'    => 'require',
            'number'           => 'require',
            'procedures_price' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $user_info_model = new UserInfo();
        $user_money      = $user_info_model->where(['uid' => $user_id, 'type' => $all['type']])->find();
        $money           = $all['number'] + $all['procedures_price'];
        if (!$user_money) {
            $this->error('资金不足');
        } else {
            if ($user_money->assets < $money) {
                $this->error('资金不足');
            }
            $all['user_id']         = $user_id;
            $all['chongti']         = 2;
            $all['create_time']     = time();
            $all['update_time']     = time();
            $user_transaction_model = new UserTransaction();
            Db::startTrans();
            try {
                $user_transaction_model->insert($all);
                $user_info_model->where('id', $user_money->id)->inc('frozen', $money)->dec('assets', $money)->update();
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error('操作失败:' . $e->getMessage());
            }
            $this->success('操作成功:');
        }
    }

    /**
     * @param Request $request
     * 我的矿机 数量总和
     */
    public function user_kj(Request $request) {
        $user             = $request->uid;
        $user_goods_count = \app\admin\model\Order::where('uid', $user)->count();
        $begintime        = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $endtime          = mktime(0, 0, 0, date('m'), date('d'), date('Y')) - 1;
        $where[]          = ['create_time', 'between', "$begintime,$endtime"];
        $where[]          = ['user_id', '=', $request->uid];
        $where[]          = ['type', 'in', '12,13,14,15,16,17'];
        $user_amount_sum  = UserAmountLog::where($where)->sum('amount');
        $commission_where = [
            ['user_id', '=', $request->uid],
            ['type', 'in', '1,2,3,4,5,18'],
        ];
        $commission       = UserAmountLog::where($commission_where)->sum('amount');
        $data             = [
            'user_goods_count' => $user_goods_count,
            'user_amount_sum'  => $user_amount_sum,
            'commission'       => $commission,
        ];
        $this->success('OK', $data);

    }

    public function user_kj_list(Request $request) {
        $uid      = $request->uid;
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'page' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $page    = isset($all['page']) && !empty($all['page']) ? $all['page'] : 1;
        $limit   = isset($all['limit']) && !empty($all['limit']) ? $all['limit'] : 15;
        $where[] = [
            ['o.uid', '=', $uid],
            ['o.type', '=', 2],
        ];

        $model = new \app\admin\model\Order();
        $data  = $model->where($where)->field('o.id as order_id,o.type_id,o.status,mg.id,mg.virtual_sales,mg.stock,mg.sales,mg.discount_price,mg.title,mg.produce_type,mg.produce,mg.type,mg.datys')->alias('o')->leftJoin('mall_goods mg', 'mg.id = o.type_id')->page($page, $limit)->order('order_id', 'desc')->select()->toArray();
        foreach ($data as $k => $v) {
            $data[$k]['status_text']  = $model->getStatusList()[$v['status']];
            $data[$k]['produce_type'] = config('cointype')[$v['produce_type']];
            if ($v['type'] == 1) {
                $data[$k]['datys'] = '次日0:00';
            } else {
                $data[$k]['datys'] = $v['datys'] . '日0:00';
            }
        }
        $this->success('OK', $data);
    }

    public function user_money(Request $request) {
        $uid  = $request->uid;
        $data = UserInfo::where('uid', $uid)->select()->toArray();
        $sum  = 0;
        foreach ($data as $k => $v) {
            $type_text = config('cointype')[$v['type']];
            if ($v['type'] !== 6) {
                $res = ClHttp::request('https://www.okex.com/api/spot/v3/instruments/' . $type_text . '-USDT/ticker', '', 'json');
                $sum += $v['assets'] * $res['last'];
            } else {
                $sum += $v['assets'];
            }
        }
        $this->success('OK', $sum . ' USDT');
    }


    public function feedback_add(Request $request) {
        $uid      = $request->uid;
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'content' => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $where = [
            'content'     => $all['content'],
            'user_id'     => $uid,
            'create_time' => time(),
            'update_time' => time(),
        ];
        SystemFeedback::insert($where);
        $this->success('感谢您的反馈！');
    }


    /**
     * 开始时间
     * 矿机类型（每日产出）
     * 投入成本
     * 电费
     * 功率（W）
     * 投入成本/（（每日产出*当前币价*换算人民币）-（24小时*功率/1000*电费））   【四舍五入】
     */
    public function current_cycle() {
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'start_time' => 'require',
            'cate_id'    => 'require',
            'cost'       => 'require',
            'electric'   => 'require',
            'power'      => 'require',
            'number'      => 'require',
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $goods = MallGoods::where(['status' => 1, 'cate_id' => $all['cate_id']])->find();
        if (!$goods) {
            $this->error('当前分类下暂无矿机');
        }
        $type_text = config('cointype')[$goods->produce_type];
        $res       = ClHttp::request('https://www.okex.com/api/spot/v3/instruments/' . $type_text . '-USDT/ticker', '', 'json');
        $res1 = $goods->produce * $res['last']*$all['number'];
        //        每日产出人民币
        $price = UserInfo::getUsdtByCny($res1);

        //        24小时的电费
        $power = 24 * $all['power'] * $all['electric'] / 1000;
        $daty  = intval($all['cost'] / ($price - $power));
        if ($daty <= 0){
            $this->error('当前计算亏本');
        }
        $this->success('success', date('Y-m-d H:i:s', strtotime("{$all['start_time']} + $daty day")));
    }

    public function is_real(Request $request) {
        $user_id = $request->uid;
        $all      = input();
        $validate = \think\facade\Validate::rule([
            'full_name' => 'require',
            'id_card' => 'require'
        ]);
        if (!$validate->check($all)) {
            $this->error(0, $validate->getError());
        }
        $all['user_id']=$user_id;
        $user_model =  new UserReal();
        $data = $user_model->save($all);
        if($data !== false){
            $this->success('实名成功，等待审核');
        }else{
            $this->error('网络错误');
        }
    }

}